package com.upup.controller;

import com.blade.mvc.annotation.*;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.blade.mvc.multipart.FileItem;
import com.upup.service.*;
import com.upup.service.impl.*;
import com.upup.util.*;

import java.io.FileOutputStream;
import java.util.Optional;

/**
 * @author : zhiye
 * @description :My's route
 */

@Path("my")
public class MyController {

    @PostRoute("register")
    @JSON
    public void register(Request request, @Param String email, @Param String username, @Param String password, Response response){
        UserService userService = new UserServiceImpl();
        if(userService.checkUsername(username)){
            response.json("{\"message\" : \"您的用户名已存在。\"}");
            return;
        }
        if(userService.checkEmail(email)){
            response.json("{\"message\" : \"您的邮箱已存在。\"}");
            return;
        }
        String time= ATool.getTime();
        Optional<FileItem> fileItem = request.fileItem( "avatar");
        fileItem.ifPresent(item ->{
            System.out.println(item);
            byte[] data = item.getData();
            try {
                FileOutputStream fos = new FileOutputStream("E:/Javaidea/chlapp/src/main/resources/static/uploads/"+time+".jpg");
                fos.write(data);
                fos.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        if (userService.saveUser(username,password,email,time)){
            response.json("{\"message\" : \"注册成功。\"}");
        }
    }

    @PostRoute("login")
    @JSON
    public void login(@Param String username,@Param String password, Response response){
        UserService userService = new UserServiceImpl();
        if(userService.checkUAP(username,password)){
            response.json("{\"message\" : \"登录成功\", \"code\" : 1}");
        }else {
            response.json("{\"message\" : \"登录失败\", \"code\" : 0}");
            return;
        }
    }
}